package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.enums.SendStatusEnum;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheQueryVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheVO;
import com.jwsoft.manager.common.vo.eduPushparents.EduPushparentsKeyVO;
import com.jwsoft.manager.common.vo.eduPushparents.EduPushparentsQueryVO;
import com.jwsoft.manager.common.vo.eduPushparents.EduPushparentsVO;
import com.jwsoft.manager.core.dao.model.EduPushparents;
import com.jwsoft.manager.core.dao.model.EduSendMessage;
import com.jwsoft.manager.core.dao.service.EduPushparentsService;
import com.jwsoft.manager.core.dao.service.EduSendMessageService;
import com.jwsoft.manager.core.integration.EduPushparentsIntegration;
import com.jwsoft.manager.core.integration.EduSystemConfigIntegration;
import com.jwsoft.manager.core.util.EduHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 是否推送信息表业务实现类
 *
 * @author zjl
 * @since 2024-04-08
 */
@ApiService(funcCode = "eduPushparents", title = "是否推送信息表")
public class EduPushparentsIntegrationImpl implements EduPushparentsIntegration {

    @Autowired
    public EduPushparentsService eduPushparentsService;
    @Autowired
    public EduSystemConfigIntegration eduSystemConfigIntegration;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    private RedisHelper redisHelper;
    @Autowired
    private EduSendMessageService eduSendMessageService;
    @Override
    @OpApi(funcCode = "eduPushparents0001", title = "是否推送信息表分页查询", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduPushparentsVO> getList(EduPushparentsQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        LambdaQueryWrapper<EduPushparents> queryWrapper =
                new QueryWrapper<EduPushparents>().lambda().eq(EduPushparents::getAreaCode, vo.getAreaCode())
                .eq(EduPushparents::getYear, vo.getYear()).orderByAsc(EduPushparents::getEnrollNum);
        List<EduPushparents> list = eduPushparentsService.list(queryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduPushparents> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduPushparentsVO> resultList = Convert.toList(EduPushparentsVO.class, pageInfo.getList());
        for (EduPushparentsVO result : resultList){
            //已推送，推送按钮不可编辑
            if (result.getPushStatus().equals("1")){
                result.setIsEditFlag(true);
            }else{
                result.setIsEditFlag(false);
            }
        }
        // 转义数据字典值
        // dictHelper.valueToName(resultList, Arrays.asList(DemoDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduPushparents0002", title = "是否推送信息表根据主键查询详情", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public EduPushparentsVO getById(EduPushparentsKeyVO vo) {
        EduPushparents entity = eduPushparentsService.getById(vo.getPushId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduPushparentsVO result = Convert.convert(EduPushparentsVO.class, entity);
        return result;
    }
    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduPushparents0003", title = "是否推送信息表保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(EduPushparentsVO vo) {
        if (StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getAreaCode());
        }
        if (StringUtils.isBlank(vo.getAreaCode())){
            throw new AppException("请选择行政区划!");
        }
        Integer year=eduHelper.thisYear();
        if (vo.getYear()==null){
            vo.setYear(year);
        }else{
            if(vo.getYear()-year!=0){
                throw new AppException("只能推送当前招生年度的数据!");
            }
        }

        if (vo.getEnrollNum()==null){
            throw new AppException("请选择第几轮报名!");
        }

        QueryWrapper<EduPushparents> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(EduPushparents::getYear,vo.getYear())
                .eq(EduPushparents::getEnrollNum,vo.getEnrollNum()).eq(EduPushparents::getAreaCode,vo.getAreaCode())
                .eq(EduPushparents::getSchoolCategory,vo.getSchoolCategory());
        List<EduPushparents> list = eduPushparentsService.list(queryWrapper);
        if (list.size()>1){
            throw new AppException("该年度该轮报名已存在推送信息!");
        }
    }

    @Override
    @OpApi(funcCode = "eduPushparents0004", title = "是否推送信息表新增", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduPushparents0004",
            operationName = "是否推送信息表新增",
            dataType = "pushId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduPushparentsVO add(EduPushparentsVO vo) {
        //保存前校验
        checkSave(vo);
        //保存数据
        vo.setPushTime(DateUtil.now());
        vo.setPushStatus("0");//待推送
        EduPushparents entity = Convert.convert(EduPushparents.class, vo);
        eduPushparentsService.save(entity);
        //将主键设置回vo使操作日志可以取到
        vo.setPushId(entity.getPushId());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduPushparents0005", title = "是否推送信息表修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduPushparents0005",
            operationName = "是否推送信息表修改",
            dataType = "pushId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduPushparentsVO edit(EduPushparentsVO vo) {
        if (ObjectUtils.isEmpty(vo.getPushId())) {
            throw new AppException("传入需要修改的主键不能为空!");
        }
        EduPushparents oldEntity = eduPushparentsService.getById(vo.getPushId());
        if (ObjectUtils.isEmpty(oldEntity)) {
            throw new AppException("查询不到需要修改的信息!");
        }
        oldEntity.setPushStatus(vo.getPushStatus());//修改推送状态
        if(vo.getPushStatus().equals("1")){
            //更新当前批次、行政区划短信发送状态
            LambdaQueryWrapper<EduSendMessage> queryWrapper = new QueryWrapper<EduSendMessage>().lambda().eq(EduSendMessage::getYear, oldEntity.getYear())
                    .eq(EduSendMessage::getEnrollNum, oldEntity.getEnrollNum())
                    .eq(EduSendMessage::getAreaCode, oldEntity.getAreaCode())
                    .eq(EduSendMessage::getSendStatus,SendStatusEnum.cg.getType());
            List<EduSendMessage> sendMessageList = eduSendMessageService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(sendMessageList)){
                LambdaUpdateWrapper<EduSendMessage> updateWrapper = new UpdateWrapper<EduSendMessage>().lambda()
                        .set(EduSendMessage::getSendStatus, SendStatusEnum.dfs.getType())
                        .eq(EduSendMessage::getYear, oldEntity.getYear())
                        .eq(EduSendMessage::getEnrollNum, oldEntity.getEnrollNum())
                        .eq(EduSendMessage::getAreaCode, oldEntity.getAreaCode())
                        .eq(EduSendMessage::getSendStatus,SendStatusEnum.cg.getType());
                eduSendMessageService.update(updateWrapper);
            }
        }
        //保存数据
        EduPushparents entity = Convert.convert(EduPushparents.class, oldEntity);
        eduPushparentsService.updateById(entity);
        //清除缓存
        Set<String> keys = redisHelper.getKeys(EduCache.EDU_MY_ENROLL + "*");
        for (String key : keys) {
            redisHelper.del(key);
        }
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduPushparents0006", title = "是否推送信息表根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduPushparents0006",
            operationName = "是否推送信息表删除",
            dataType = "pushId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduPushparentsKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getPushId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduPushparents entity = eduPushparentsService.getById(vo.getPushId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduPushparentsService.removeById(vo.getPushId());
    }

    @Override
    @OpApi(funcCode = "eduPushparents0007", title = "是否推送信息表查询当前第几轮报名", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public EduPushparentsQueryVO getErollNum(EduPushparentsQueryVO vo) {
        Integer year=eduHelper.thisYear();
        String areaCode= SessionUtil.getAreaCode();
        if(StringUtils.isBlank(areaCode)){
            areaCode=eduHelper.thisAreaCode();
        }
        EduOperationCacheQueryVO queryVO=new EduOperationCacheQueryVO();
        queryVO.setClassify("2");
        queryVO.setAreaCode(areaCode);
        queryVO.setYear(year);
        EduOperationCacheVO eduOperationCacheVO=eduSystemConfigIntegration.getEduOperation(queryVO);
        Map<String, EduOperationCacheDetailVO> operation=eduOperationCacheVO.getOperation();
        long curTime = DateUtil.currentSeconds();
        EduOperationCacheDetailVO oneOperation=operation.get("YW002");
        EduOperationCacheDetailVO twoOperation=operation.get("YW022");
        EduOperationCacheDetailVO bbTwoOperation=operation.get("YW072");//第二批第二轮
        EduOperationCacheDetailVO threeOperation=operation.get("YW010");
        //第一轮报名开始之后，第二轮报名开始之前都是第一轮报名
        if(oneOperation!=null&&twoOperation!=null&&threeOperation!=null){

            Date oneBegDate=oneOperation.getBegTime();//第一轮开始时间
            Date twoBegDate=twoOperation.getBegTime();//第二轮开始时间
            Date twobbBegDate=bbTwoOperation!=null?twoOperation.getBegTime():null;//第二轮第二次
            Date threeBegDate=threeOperation.getBegTime();//第三轮开始时间
            Date threeEndDate=threeOperation.getEndTime();//第三轮结束时间
            if (oneBegDate==null||oneBegDate.getTime() / 1000 - curTime > 0) {
                throw new AppException("报名未开始");
            }
            if (threeEndDate!=null&&threeEndDate.getTime() / 1000 - curTime <0) {
                throw new AppException("报名已结束");
            }
            if((twoBegDate==null||twoBegDate.getTime()/1000-curTime>0)&&oneBegDate.getTime()/1000-curTime<0){
                vo.setEnrollNum(1);
            }
            if((threeBegDate==null||threeBegDate.getTime()/1000-curTime>0)&&(twoBegDate!=null&&twoBegDate.getTime()/1000-curTime<0)){
                vo.setEnrollNum(2);
            }
            if((twobbBegDate==null||twobbBegDate.getTime()/1000-curTime>0)&&(twoBegDate!=null&&twoBegDate.getTime()/1000-curTime<0)){
                vo.setEnrollNum(2);
            }
            if((threeBegDate==null||threeBegDate.getTime()/1000-curTime>0)&&(twobbBegDate!=null&&twobbBegDate.getTime()/1000-curTime<0)){
                vo.setEnrollNum(3);
            }
            if (threeBegDate!=null&&threeBegDate.getTime()/1000-curTime<0){
                vo.setEnrollNum(3);
            }
        }
        return vo;
    }
}
